<template>
  <div class="role-admin">
    <div class="add-interface">
      <el-button type="primary" @click="addRole()" v-if="searchInterface('roles.store')">添加角色</el-button>
    </div>
    <!-- 角色列表 -->
    <el-table :data="roleList" border style="width: 100%" v-loading="loading">
      <el-table-column width="100" label="序号" header-align="center" align="center">
        <template slot-scope="scope">
          <div>{{pages.per_limit*(pages.page-1)+scope.$index+1}}</div>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="name" label="角色类型" width="300"></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="created_at"
        label="添加时间"
        width="400"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="updated_at"
        label="更新时间"
        width="400"
      ></el-table-column>
      <el-table-column header-align="center" align="center" fixed="right" label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="editRole(scope.row)"
            :disabled="scope.row.is_super===1"
            v-if="searchInterface('roles.update')"
          >编辑</el-button>
          <el-button
            @click="deleteRole(scope.row,scope.$index)"
            type="danger"
            :disabled="scope.row.is_super===1"
            v-if="searchInterface('roles.destroy')"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="footer">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="pages.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pages.per_limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 新增菜单 -->
    <el-dialog
      :title="(isAdd?'新增':'编辑')+'角色？'"
      :visible.sync="dialogVisible"
      width="35%"
      @close="cancel"
    >
      <el-form label-width="140px" :rules="rules" :model="role" ref="role">
        <!-- 接口 -->
        <div>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model.trim="role.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="菜单配置" prop="title">
            <el-tree
              :data="menus"
              :props="defaultProps"
              node-key="id"
              ref="menuTree"
              show-checkbox
              :expand-on-click-node="false"
              :render-content="renderContent"
            ></el-tree>
          </el-form-item>
          <el-form-item label="接口配置" prop="title">
            <el-tree
              :data="interfaces"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              ref="interfaceTree"
              :expand-on-click-node="false"
              :render-content="renderContent"
            ></el-tree>
          </el-form-item>
          <el-form-item label="是否显示?">
            <el-switch v-model="role.is_enable" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel('role')">取 消</el-button>
        <el-button type="primary" @click="submit('role')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getMenuList } from '@/api/user-center/menu'
import { getPermissionList } from '@/api/user-center/permission'
import { date } from '@/utils'
import {
  getRolesList,
  addRole,
  editRole,
  deleteRole
} from '@/api/user-center/role'
import { menu } from '@/utils'
export default {
  data() {
    return {
      isGetMenuAndPermission: false,
      pages: {
        page: 1,
        per_limit: 10
      },
      total: 0,
      loading: false,
      defaultCheckedKeys: [],
      roleList: [],
      menus: [],
      childMenus: [],
      interfaces: [],
      childInterfaces: [],
      roles: [],
      dialogVisible: false,
      isAdd: true,
      editData: [],
      role: {
        name: '',
        menus: [],
        permissions: [],
        is_enable: true
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      menuProps: {
        value: 'id',
        label: 'title'
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  beforeMount() {
    this.getRolesList()
  },
  methods: {
    handleChange(data) {},
    // 获取角色列表
    getRolesList() {
      this.loading = true
      getRolesList(this.pages)
        .then(res => {
          const {
            data,
            meta: {
              pagination: { total }
            }
          } = res
          data.forEach(i => {
            i.updated_at = date.formatDate(i.updated_at)
            i.created_at = date.formatDate(i.created_at)
          })
          this.roleList = data
          this.total = total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取菜单
    getMenuList() {
      return new Promise((resolve, reject) => {
        getMenuList()
          .then(res => {
            menu.handleMenu(res)
            this.childMenus = res.map(i => {
              if (!i.children) {
                return i.id
              }
            })
            this.menus = menu.generateMenu(res)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取权限
    getPermissionList() {
      return new Promise((resolve, reject) => {
        getPermissionList()
          .then(res => {
            menu.handleMenu(res)
            this.childInterfaces = res.map(i => {
              if (!i.children) {
                return i.id
              }
            })
            this.interfaces = menu.generateMenu(res)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 新增或者编辑角色
    submit(formName) {
      const menus = this.$refs['menuTree']
        .getCheckedNodes(false, true)
        .map(({ id }) => id)
      const permissions = this.$refs['interfaceTree']
        .getCheckedNodes(false, true)
        .map(({ id }) => id)
      this.$refs[formName].validate(valid => {
        if (valid) {
          const { name, is_enable, id } = this.role
          let params = { name, is_enable }
          params.is_enable = is_enable ? 1 : 0
          params.menus = menus
          params.permissions = permissions
          if (this.isAdd) {
            addRole(params).then(() => {
              this.$message.success('新增成功')
              this.getRolesList()
              this.dialogVisible = false
            })
          } else {
            editRole({ params, id }).then(() => {
              this.$message.success('编辑成功')
              let roleList = this.roleList
              let item = roleList.find(i => i.id === id)
              Object.assign(item, params)
              this.roleList = roleList
              this.dialogVisible = false
            })
          }
        }
      })
    },
    // 取消
    cancel(formName = 'role') {
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },
    // 新增菜单
    addRole() {
      this.isAdd = true
      this.dialogVisible = true
      this.resetParams()
      this.mergeRequest()
      this.setKey()
    },
    // 重置参数
    resetParams() {
      this.role = {
        name: '',
        menus: [],
        permissions: [],
        is_enable: true
      }
    },
    // 删除菜单
    deleteRole({ id }, index) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '删除角色操作？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole(id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.roleList.splice(index, 1)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 合并请求
    mergeRequest() {
      return new Promise(async (resolve, reject) => {
        if (!this.isGetMenuAndPermission) {
          await this.getMenuList()
          await this.getPermissionList()
          this.isGetMenuAndPermission = true
          resolve()
        } else {
          resolve()
        }
      })
    },
    // 编辑角色
    async editRole(list) {
      await this.mergeRequest()
      this.isAdd = false
      this.dialogVisible = true
      const { name, is_enable, menus, permissions, id } = list
      this.role = {
        name,
        menus,
        id,
        permissions,
        is_enable: is_enable === 1 ? true : false
      }
      this.setKey(menus, permissions)
    },
    // 设置选中的key
    setKey(menus = [], permissions = []) {
      setTimeout(() => {
        // 去掉重复数据
        let permissionKeys = []
        let menukeys = []
        permissions.map((i, index) => {
          if (this.childInterfaces.indexOf(i) !== -1) {
            permissionKeys.push(i)
          }
        })
        menus.map((i, index) => {
          if (this.childMenus.indexOf(i) !== -1) {
            menukeys.push(i)
          }
        })
        this.$refs['menuTree'].setCheckedKeys(menukeys)
        this.$refs['interfaceTree'].setCheckedKeys(permissionKeys)
      })
    },
    // 渲染接口
    renderContent(h, { node, data, store }) {
      return (
        <span style="flex:0.2;display: flex;align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span>
            <span>{node.label}</span>
          </span>
        </span>
      )
    },
    // 切换页码
    currentChange(value) {
      this.pages.page = value
      this.getAdminList()
    },
    sizeChange(value) {
      this.pages.per_limit = value
      this.getAdminList()
    }
  }
}
</script>

<style lang="scss">
.role-admin {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
  .add-interface {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }
  .footer {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>